package com.laycoding.layrpc.handler.client;

import com.alibaba.fastjson.JSONObject;
import com.laycoding.layrpc.common.LayRpcRegistryCache;
import com.laycoding.layrpc.entity.LayRpcMessage;
import com.laycoding.layrpc.entity.LayRpcResponse;
import com.laycoding.layrpc.handler.client.handler.HeartBeatHandler;
import com.laycoding.layrpc.handler.client.handler.IdleStateTriggerHandler;
import com.laycoding.layrpc.handler.client.handler.LayRpcClientInitializer;
import com.laycoding.layrpc.handler.client.handler.ReconnectHandler;
import com.laycoding.layrpc.handler.client.retry.ExponentialBackOffRetry;
import com.laycoding.layrpc.handler.client.retry.RetryPolicyService;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.codec.serialization.ClassResolvers;
import io.netty.handler.codec.serialization.ObjectDecoder;
import io.netty.handler.codec.serialization.ObjectEncoder;
import lombok.Data;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.configurationprocessor.json.JSONArray;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Deque;
import java.util.LinkedList;
import java.util.concurrent.SynchronousQueue;

@Data
public class LayRpcClientRegistry implements DisposableBean {

    @Autowired
    private RpcProxyHandler rpcProxyHandler;

    EventLoopGroup group = new NioEventLoopGroup();

    Bootstrap bootstrap = new Bootstrap();

    private String host;

    private Integer port;

    private RetryPolicyService retryPolicyService = new ExponentialBackOffRetry(1000, 10, 60 * 1000);

    private Channel channel;

    public LayRpcClientRegistry() {
    }

    public void connect() {
        try {
            synchronized (bootstrap) {
                ChannelFuture future = bootstrap.connect(host, port);
                this.channel = future.channel();
                future.addListener(new ChannelFutureListener() {
                    @Override
                    public void operationComplete(ChannelFuture future) throws Exception {
                        if (!future.isSuccess()) {
                            future.channel().pipeline().fireChannelInactive();
                        } else {
                            LayRpcRegistryCache.putChannel(future.channel(), "rpcservice");
                        }
                    }
                });
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }
    @PostConstruct
    public void init() {
        try {
            bootstrap.group(group)
                    .channel(NioSocketChannel.class)
                    .option(ChannelOption.TCP_NODELAY, true)
                    .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 3000)
                    .handler(new LayRpcClientInitializer(rpcProxyHandler, LayRpcClientRegistry.this));
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }


    @Override
    public void destroy() throws Exception {
        LayRpcRegistryCache.CloseAll();
        group.shutdownGracefully();
    }

    public LayRpcResponse sendMessage(LayRpcMessage msg) throws InterruptedException {
        Deque<Integer> deque = new LinkedList<>();

        Channel channel = LayRpcRegistryCache.getChannel("rpcservice");
        LayRpcResponse response = new LayRpcResponse();
        response.setRpcId(msg.getRpcId());
        if (channel != null && channel.isActive()) {
            SynchronousQueue<Object> queue = rpcProxyHandler.sendRequest(msg, channel);
            LayRpcResponse result = (LayRpcResponse) queue.take();
            response.setData(result.getData());
            return response;
        } else {
            response.setData("未正确连接到服务器.请检查相关配置信息!");
            return response;
        }
    }

    public RetryPolicyService getRetryPolicyService() {
        return retryPolicyService;
    }
}
